<template>
  <div class="report_form_dialog">
    <!-- 修改发送日报弹框 -->
    <!-- :append-to-body="true" -->
    <el-dialog
      v-model="visible"
      :title="`${isEdit ? '编辑' : '新建'}发送日报`"
      :show-close="false"
      :close-on-click-modal="false"
      top="10vh"
      center
      :width="isPhone ? '94%' : '800px'"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="90px"
          >
            <el-form-item label="模块名称" prop="moduleIds">
              <ProjectModuleCascade
                ref="projectModuleCascadeRef"
                :moduleNames="form.moduleNames"
                @change="changeModuleIds"
              />
            </el-form-item>

            <!-- <el-form-item label="分隔符" prop="splitChar">
              <el-input v-model="form.splitChar"></el-input>
            </el-form-item> -->

            <el-form-item label="工作内容" prop="reportText">
              <el-input
                type="textarea"
                rows="7"
                v-model="form.reportText"
              ></el-input>
            </el-form-item>

            <el-form-item label="工作进度" prop="workProgress">
              <el-slider v-model="form.workProgress"></el-slider>
            </el-form-item>

            <el-form-item label="快捷选进度">
              <el-button size="small" @click="form.workProgress = 50">
                50%
              </el-button>
              <el-button size="small" @click="form.workProgress = 90">
                90%
              </el-button>
              <el-button size="small" @click="form.workProgress = 100">
                100%
              </el-button>
            </el-form-item>

            <el-form-item
              v-if="userInfo.isLeader && !isEdit"
              label="报告人"
              prop="reportName"
            >
              <el-select
                v-model="form.creatorId"
                value-key="id"
                filterable
                placeholder="请选择"
                size="small"
                @change="changeReportName"
              >
                <el-option
                  v-for="item in userSelectList"
                  :key="item.id"
                  :label="item.truename || item.nickname"
                  :value="item.id"
                  :disabled="!item.truename"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="日期时间">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.date1"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item> -->
          </el-form>
        </div>

        <div style="text-align: center; padding-top: 30px">
          <el-button
            type="primary"
            :loading="confirmBtnLoading"
            @click="onAddMethod"
          >
            确定
          </el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, computed } from "vue";
import { useStore } from "vuex";
import { cloneDeep } from "lodash";
import ProjectModuleCascade from "../../../components/ProjectModuleCascade.vue";

const initFormData = () => {
  return {
    id: null,
    moduleIds: null,
    moduleNames: null,
    // splitChar: "、",
    reportText: null,
    workProgress: 0,
    reportTime: null,
    creatorId: null,
    reportName: null,
    // 作为新增的数据唯一的鉴别凭证
    createdTime: null,
  };
};

let reportType = null;
let oldReport = null;

export default {
  name: "ReportCommitFormEditDialog",
  components: { ProjectModuleCascade },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $moment = proxy.$moment;
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);
    const isPhone = computed(() => store.state.isPhone);

    const isEdit = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 级联组件的引用
    const cascaderRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      reportText: [
        { required: true, message: "请输入工作内容", trigger: "blur" },
      ],
      workProgress: [
        { required: true, message: "请选择工作进度", trigger: "blur" },
      ],
      reportName: [
        { required: true, message: "请选择报告人", trigger: "blur" },
      ],
    });

    const projectModuleCascadeRef = ref(null);

    // 选择模块
    const changeModuleIds = ({ moduleIds, moduleNames }) => {
      // console.log("changeModuleIds => ", { moduleIds, moduleNames });
      if (moduleIds && moduleNames) {
        form.moduleIds = moduleIds;
        form.moduleNames = moduleNames;
      }
    };

    // 立即添加
    const onAddMethod = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          // dialogLoading.value = true;
          // console.log("form ===> ", form);
          // 此处必须要使用 cloneDeep
          // 新增数据手动添加一个创建时间，作为新增的数据鉴别凭证
          if (!isEdit.value) {
            form.createdTime = $moment().format("YYYY-MM-DD HH:mm:ss");
          }
          context.emit("confirm", cloneDeep(form), reportType, oldReport);
          close();
        }
      });
    };

    // 打开弹框
    const open = (row, type) => {
      reportType = type;
      if (row) {
        oldReport = row;
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
        listUserByGroupId();
        // 如果不是组织管理员，设置默认报告人
        form.reportName = userInfo.value.truename;
        form.creatorId = userInfo.value.id;
      }
      projectModuleCascadeRef.value &&
        projectModuleCascadeRef.value.refreshData();
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      resetData();
      visible.value = false;
      reportType = null;
      oldReport = null;
    };

    // 重置
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 清空级联
      projectModuleCascadeRef.value && projectModuleCascadeRef.value.clear();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    const userSelectList = ref([]);

    // 获取没有组织的人员数据
    const listUserByGroupId = () => {
      $api.users
        .listUserByGroupId({
          groupId: userInfo.value.groupId,
        })
        .then((res) => {
          userSelectList.value = res.data;
        })
        .catch((err) => {
          console.error("listUserByGroupId error: ", err);
        });
    };

    const changeReportName = (val) => {
      const user = userSelectList.value.find((item) => item.id === val);
      if (user) {
        form.reportName = user.truename;
      } else {
        form.reportName = null;
      }
    };

    return {
      userInfo,
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      cascaderRef,
      form,
      rules,
      isPhone,
      open,
      close,
      resetData,
      changeModuleIds,
      onAddMethod,
      projectModuleCascadeRef,
      isEdit,
      userSelectList,
      changeReportName,
    };
  },
};
</script>

<style lang="less" scoped>
.report_form_dialog {
}
</style>
